<!--出库-集包打板-->
<template>
  <div class="page-container">
    <page_breadcrumb pageOption :getKeyMethod="init_table_model" @change="change_table_model"
      modelPath="tableOption.model" />

    <el-form label-position="right" ref="formSearch" onsubmit="return false" :rules="rules" :model="{}">

      <el-form-item :label="$tt('label_search')" class=" mg_t2" prop="searchCode">
        <div class="flex_row_center ">
          <scan_input v-model.trim="searchCode" @enterInput="scanTrackNumber" style="width:450px"
            class="form_input_default mg_l1" autofocus>
            <el-select v-model="searchType" slot="prepend" style="width:130px">
              <el-option :label="$tt('label_face_track_code')" value="track"></el-option>
              <el-option :label="$tt('label_collect_code')" value="collect"></el-option>
            </el-select>
          </scan_input>

          <el-button class="mg_l2" type="primary" @click="scanTrackNumber">
            {{ $tt('label_scan') }}</el-button>
          <el-checkbox class="mg_1" :value="autoPrint" border @input="changeAutoPrint">
            {{ $tt('label_auto_print') }}
          </el-checkbox>
        </div>
      </el-form-item>
    </el-form>
    <div class="flex_auto mg_l2 flex_row card_1 mg_1" style="overflow: hidden;">

      <transition name="el-zoom-in-center" mode="out-in" :duration="250">
        <template v-if="linkLoading">
          <div v-loading="linkLoading" class="flex_auto flex_center mg_1 ">
            <!-- <div v-show="linkError" class="color_info">{{ $tt('label_get_track_info_fail') }}</div> -->
          </div>
        </template>

        <div v-else-if="trackList.length > 0 || hasCollectTrackList" class="flex_row flex_auto">
          <div class="flex_cell flex_col " key="trackLinkTableDiv">
            <div class="mg_v2 bold">
              {{ $tt('tip_has_build_collect_package_code') }} : [ {{ boardNo }} ] &nbsp;,&nbsp;
              {{ $tt('tip_current_collect_package_content') }}
            </div>
            <div class="flex_cell" style="position: relative;">
              <div style="position: absolute;width: 100%;top:0;bottom: 0;">
                <ex_super_table class="h_fill" :data="trackList" v-bind="palletTableOption" border height="100%"
                  key="palletTableOption">
                </ex_super_table>
              </div>
            </div>

            <el-form :inline="true" ref="FormPack" class="mg_t1">
              <ex_super_input v-model="collectionPackType" type="select" :attrs="{
      i18n: true,
      items: [{ label: 'label_PackMaterial', value: 'PackMaterial' }, { label: 'label_PackContainer', value: 'PackContainer' }]
    }" class="form_input_small" @change="changeCollectionPackType" />
              <el-form-item :label="$tt('label_container_type')" v-if="collectionPackType == 'PackContainer'">
                <!-- <ex_super_input v-model="containerType" type="select" enum="PackTypeList" class="form_input_mini" /> -->
                <container_selec_input v-model="containerId" :code.sync="containerCode" :typeCode.sync="containerType"
                  @changeItem="(e) => {
      containerCode = e ? e.code : ''
      containerType = e ? e.containerTypeCode : ''
    }" :clearable="true" />
              </el-form-item>
              <el-form-item :label="$tt('label_pack_material')" v-else>
                <pack_material_cascader class="form_input_small" :packId.sync="packId" :packName.sync="packName"
                  :packCode.sync="packCode" :typeId.sync="packTypeId" :typeName.sync="packTypeName" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="confirmPackageCheck">
                  {{ $tt('label_confirm_package_collection') }}
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="warning" @click="reportAnomaly">
                  {{ $tt('label_report_exception') }}
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="warning" @click="pausePackage">
                  {{ $tt('label_pause_package_collection') }}
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class=" flex_col mg_l1" key="trackCollectTableDiv" v-if="hasCollectTrackList" style="width: 400px;">
            <div class="mg_v2 bold" style="text-align: end;">
              {{ $tt('label_wait_scan_order_count') }} : [ {{ hasCollectTrackList.filter(it => !it.finish).length }} ]
            </div>
            <ex_super_table :data="hasCollectTrackList.filter(it => !it.finish)" v-bind="collectTableOption" border
              :autoFlex="true" height="auto" key="collectTableOption">
            </ex_super_table>
          </div>
        </div>

        <template v-else>
          <div class="flex_auto flex_center  mg_1 ">
            <div class="color_info">{{ $tt('tip_scan_track_code_first') }}</div>
          </div>
        </template>
      </transition>
    </div>

    <div class="flex_row flex_justify_sb mg_v2">
      <div></div>
      <div class="flex_row">
        <el-button type="primary" @click="reviewConfirm">{{ $tt('label_audit_confirm') }}</el-button>
        <el-button @click="goToRecord">{{ $tt('title_package_collection_record') }}</el-button>
      </div>
    </div>


    <ex_super_table class="main-table" v-bind="tableOption" :data="tableData" :autoFlex="true" :autoPage="false"
      :specialStyle="false" :span-method="objectSpanMethod">
    </ex_super_table>
    <ex_super_dialog_form ref="measureFormDialog" :title="$tt('label_check_pack_measure')" v-bind="measureDialog"
      @afterSubmitSuccess="measureSubmit" />
    <report_anomaly ref="report_anomaly" :orderTypeList="['OUTBOUND']" system="WMS" :extraModel="[
      { key: 'trackNumber', label: 'label_face_track_code', formType: 'text', },
    ]" />
    <print_outbound_pallet ref="print_outbound_pallet" />

    <print_config_dialog ref="print_config_dialog" printType="BOARD" @saveConfig="saveConfig" />

  </div>
</template>
<script>
import print_config_dialog from "@/component/print/common_print_config_dialog.vue"

import superTablePageFunction from '@/mixin/super-table-page-function';

import page_table_model_manage from '@/mixin/page_table_model_manage';
import report_anomaly from '@/component/dialog/report_anomaly.vue'

import router_params from '@/mixin/router_params';

import container_selec_input from '@/component/wms/container_selec_input.vue';
import pack_material_cascader from '@/component/wms/pack_material_cascader.vue';

import print_outbound_pallet from '@/component/print/print_outbound_pallet.vue'
import auto_weight_input from '@/component/serial_port/auto_weight_input.vue'

export default {
  title: "title_package_collection",
  mixins: [superTablePageFunction, page_table_model_manage, router_params],
  components: { pack_material_cascader, container_selec_input, print_outbound_pallet, report_anomaly, auto_weight_input, print_config_dialog, },
  data() {
    return {
      isConfirm_routeParamsChange: false,
      searchCode: "",
      searchType: "track",
      rules: {
        searchCode: {
          trigger: 'blur',
          validator: (r, v, cb) => {
            if (_.isEmpty(this.searchCode)) {
              return cb(this.$tt('tip_can_no_empty'))
            }
            cb()
          }
        },
      },
      boardNo: "",
      linkLoading: false,
      linkError: false,
      autoPrint: false,

      linkTrackNumber: "",
      boxId: "",
      trackList: [],

      hasCollectTrackList: null,

      collectionPackType: "PackMaterial",

      containerType: null,
      containerId: null,
      containerCode: null,


      packId: null,
      packCode: null,
      packName: null,
      packTypeName: null,
      packTypeId: null,

      tableData: [],
      tableOption: {
        model: this.init_table_model(),
      },
      palletTableOption: {
        'show-summary': true, 'summary-method': this.getSummaries,
        model: [
          { key: 'trackNumber', label: 'label_face_track_code', 'min-width': 120, },
          {
            key: 'customerName', label: 'label_customer_name', 'width': 120, 'show-overflow-tooltip': true,
            formatter: (r, c, v, i) => this.$formatNameCode(v, r.customerCode)
          },
          { key: 'bizType', label: 'label_business_type', 'width': 120, formatter: (r, c, v) => this.$enumShow(v, "BizTypeEnum") },

          { key: 'outOrderNo', label: 'label_outbound_code', 'min-width': 120, },
          { key: 'packageBoxNos', label: 'label_box_code', 'min-width': 120, },

          { key: 'weight', label: 'label_check_pack_weight', 'width': 100, 'show-overflow-tooltip': true },
          { key: 'volume', label: 'label_check_pack_volume', 'width': 100, 'show-overflow-tooltip': true },
          { key: 'scansCount', label: 'label_sku_count', 'width': 100, 'show-overflow-tooltip': true },
          { key: 'packingName', label: 'label_pack_material_name', 'width': 100, 'show-overflow-tooltip': true },
          {
            type: 'operate', width: 140, fixed: 'right', operate: [
              {
                label: 'label_remove', class: 'button_text_danger', click: (row, i, list) => {
                  this.removeTrack(row, i, list)
                }
              }
            ]
          },
        ]
      },
      collectTableOption: {
        model: [
          { key: 'trackNumber', label: 'label_face_track_code', 'min-width': 120, 'show-overflow-tooltip': true },

          {
            key: 'customerName', label: 'label_customer_name', 'width': 120, 'show-overflow-tooltip': true,
            formatter: (r, c, v, i) => this.$formatNameCode(v, r.customerCode),
          },
          { key: 'bizType', label: 'label_business_type', 'width': 120, formatter: (r, c, v) => this.$enumShow(v, "BizTypeEnum") },

          {
            key: 'packageFlag', label: 'label_pack_status', 'width': 110, 'show-overflow-tooltip': true,
            render: (h, { row, column }) => {
              const value = row[column.property]
              const className = value == 'Y' ? 'color_success' : 'color_danger'
              return <div class={className}>
                {this.$enumShow(value, 'YesOrNoEnum')}
              </div>
            },
          },


        ]
      },
      measureDialog: {
        customClass: 'dialog_auto',
        form: {
          itemClass: "form_item_default", inputClass: "form_input_default",
          model: [
            { key: 'boardNo', label: 'label_package_collection_no', disabled: true, },
            {
              key: 'weight', label: 'label_package_collection_weight', //append: 'KG', appendClass: 'input_slot_div_mini',
              render: (h, { data }) => {
                return h(auto_weight_input,{
                  key:"AutoWeight=" + data.boardNo,class:"form_input_default",
                  props:{
                    value:data.weight,
                  },
                  on:{
                    input:e => this.$set(data, "weight", e)
                  }
                })
              }
            },
            { key: 'length', label: 'label_package_collection_length', append: 'CM', appendClass: 'input_slot_div_mini' },
            { key: 'width', label: 'label_package_collection_width', append: 'CM', appendClass: 'input_slot_div_mini' },
            { key: 'height', label: 'label_package_collection_height', append: 'CM', appendClass: 'input_slot_div_mini' },

          ],
          rules: {
            'boardNo': {
              required: true, trigger: 'blur', validator: (r, v, cb) => {
                if (_.isEmpty(v)) return cb(this.$tt('tip_can_no_empty'))
                if (this.tableData.every(it => it.boardNo != v)) {
                  return cb(this.$tt('tip_package_code_no_found_place_check'))
                }
                cb()
              },
            },
            'weight': {
              required: true, trigger: 'blur', validator: (r, v, cb) => {
                if (!v) {
                  return cb(this.$tt('tip_can_no_empty'))
                } else if (Number.isNaN(Number(v))) {
                  cb(this.$t('tip_format_error'))
                }
                cb()
              },
            },
            'length': {
              required: true, trigger: 'blur', validator: (r, v, cb) => {
                this.$reg.DigitNumber(v, 3, 9) ? cb() : cb(this.$tt("tip_check_decimal_digit_int", { digit: 3, int: 9 }))
              },
            },
            'width': {
              required: true, trigger: 'blur', validator: (r, v, cb) => {
                this.$reg.DigitNumber(v, 3, 9) ? cb() : cb(this.$tt("tip_check_decimal_digit_int", { digit: 3, int: 9 }))
              },
            },
            'height': {
              required: true, trigger: 'blur', validator: (r, v, cb) => {
                this.$reg.DigitNumber(v, 3, 9) ? cb() : cb(this.$tt("tip_check_decimal_digit_int", { digit: 3, int: 9 }))
              },
            },
          },
        }
      },

    };
  },
  mounted() {

    let localConfig = window.localStorage.getItem('outbound>package_collection>config')
    if (localConfig) {
      try {
        localConfig = JSON.parse(localConfig)
        this.autoPrint = !!localConfig.autoPrint
      } catch (e) {
      }
    }

    if (this.autoPrint) {
      const printConfig = _.head(this.$refs.print_config_dialog.loadPrintConfig({ typeKey: "BOARD" }))
      if (!printConfig || !printConfig.clientId || !printConfig.templateId) {
        this.autoPrint = false
      }
    }
    //////////////////


  },

  methods: {
    configChange() {
      const data = {
        autoPrint: this.autoPrint,
      }
      window.localStorage.setItem('outbound>package_collection>config', JSON.stringify(data))
    },

    changeAutoPrint(e) {
      if (!this.autoPrint) {
        const printConfig = _.head(this.$refs.print_config_dialog.loadPrintConfig({ typeKey: "BOARD" }))
        if (!printConfig || !printConfig.clientId || !printConfig.templateId) {
          this.autoPrint = false
          this.$refs.print_config_dialog.show()
          return
        } else {
          this.autoPrint = true
        }
      } else {
        this.autoPrint = false
      }
      this.configChange()
    },
    saveConfig() {
      const printConfig = _.head(this.$refs.print_config_dialog.loadPrintConfig({ typeKey: "BOARD" }))
      if (!printConfig || !printConfig.clientId || !printConfig.templateId) {
      } else {
        this.autoPrint = true
        this.configChange()
      }
    },
    init_data_default(into_params) {
      let params = into_params
      let search = params
      if (!_.isEmpty(search)) {
        if (search.boardNo) {
          this.$ajax({
            url: "/wms-api/outbound/OutboundBoxRpc/selectBoxDetailByBoxNo.json",
            method: 'post', loading: true,
            data: {
              boxNo: search.boardNo.trim()
            },
            success: (res) => {
              if (res.data) {
                if (res.data.packageList && res.data.boxRelationFlag == 'Y') {
                  this.checkCollectRalation(res.data.boxNo,
                    {
                      success: (data) => {
                        // this.boardNo = res.data.boxNo
                        this.boxId = res.data.id
                        res.data.packageList.forEach(pack => {
                          this.addPackageToCollectRalation(pack.trackNumber, false,)
                        })
                        // console.log(JSON.stringify(this.trackList))
                      },
                      fail: () => {
                      }
                    }
                  )
                } else {
                  this.boardNo = res.data.boxNo
                  this.boxId = res.data.id
                  res.data.packageList.forEach(pack => {
                    pack.boxId = res.data.id
                  })
                  this.trackList = res.data.packageList


                }
              }
            },
            failure: () => {
              this.boxId = null
            },
            complete: () => {
            }
          })
        }

      } else {
        this.boxId = null
      }
    },

    removeTrack(row, i, list) {
      this.$set(row, 'finish', false)
      const item = this.trackList.splice(i, 1)
      // if (this.hasCollectTrackList) {
      //   const has = _.find(this.hasCollectTrackList, it => it.trackNumber == item.trackNumber)
      //   this.$set(has, 'finish', false)
      // }
    },

    getSummaries(params) {
      const { columns, data } = params;
      const sums = columns.map((column, index) => {
        if (index === 0) {
          return this.$tt('tip_sum_total');
        }
        if (!['scansCount', 'volume', 'weight'].includes(column.property)) {
          return 'N/A';
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          return values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return this.$math_add(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        } else {
          return 'N/A';
        }
      });
      return sums;
    },
    option_table_model() {
      return [
        { key: 'boardNo', label: 'label_package_collection_no', 'min-width': 140, },
        { key: 'packageNo', label: 'label_face_track_code', 'min-width': 140, },
        { key: 'bizType', label: 'label_business_type', 'width': 120, formatter: (r, c, v) => this.$enumShow(v, "BizTypeEnum") },
        {
          key: 'customerName', label: 'label_customer_info', 'width': 120, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$formatNameCode(v, r.customerCode)
        },
        { key: 'trackWeight', label: 'label_check_pack_weight', 'width': 80, },
        { key: 'trackVolume', label: 'label_check_pack_volume', 'width': 80, },
        {
          key: 'weight', label: 'label_collect_pack_weight', 'width': 100,
          formatter: (r, c, v, i) => this.$addUnit(this.$formatDigit(v, 3), "kg"),
        },
        {
          key: 'size', label: 'label_collect_pack_size', 'width': 130,
          formatter: (r, c, v, i) => this.$addUnit(
            [this.$formatDigit(r.length, 2), this.$formatDigit(r.width, 2), this.$formatDigit(r.height, 2)].join('*')
            , "cm"),
        },
        { key: 'packageName', label: 'label_pack_material_name', 'width': 100, 'show-overflow-tooltip': true, },
        { key: 'containerCode', label: 'label_container_code', 'width': 100, 'show-overflow-tooltip': true, },
        { key: 'packageBoxNos', label: 'label_box_code', 'min-width': 120, },
        { key: 'skuCount', label: 'label_sku_count', 'width': 80, },

        {
          type: 'operate', width: 210, operate: [
            {
              label: 'label_collect_pack_mark',
              click: (row) => this.$refs.print_outbound_pallet.show([row], { single: true, }),
            },
            {
              label: 'label_third_party_collect_pack_mark', if: row => !!row.filePath,
              click: (row) => this.$refs.print_outbound_pallet.show([row], { thirdParty: true, single: true, }),
            },
            {
              label: 'label_check_pack_measure', click: (row) => this.measureFunction(row)
            },
            {
              label: 'label_cancel', type: "confirm-button", message: 'text_confirm_sure_cancel',
              buttonClass: "button_text_danger", confirmButtonType: 'danger',
              done: (row, i) => {
                this.$confirm(this.$tt('tip_confirm_cancel_pack_will_remove_all_track'), this.$tt("label_tip"), {
                  type: 'warning'
                }).then(() => {
                  this.tableData.splice(i, row.rowspan)
                }).catch(() => {

                });

              }
            },
          ],
        }
      ]
    },
    reportAnomaly() {
      this['$refs']['report_anomaly'].showNew({
        formDisabled: true,
        detailUrl: '/wms-api/outbound/OutboundBoxPackageRpc/getOrderInfo.json',
        params: { trackNumber: this.linkTrackNumber },
        detailDataHandle: (data) => {
          return {
            customerId: data.customerId,
            customerCode: data.customerCode,
            customerName: data.customerName,
            orderType: 'OUTBOUND',
            orderNo: data.outOrderNo,
            trackNumber: this.linkTrackNumber,
          }
        },

      })

    },

    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      let _list = ['boardNo', 'containerType', 'size', 'weight']
      if (_list.some(it => it == column.property) || column.type == 'operate') {
        return { rowspan: row.rowspan, colspan: 1 }
      }
    },
    goToRecord() {
      this.$router.push({ path: "/page/wms/overseas/outbound/package_collection_record", query: { userName: this.$loginUser.userName } });
    },
    measureFunction(row) {
      this['$refs']['measureFormDialog'].show(row ? _.cloneDeep(row) : {}, true)
    },
    measureSubmit(data) {
      this.tableData.forEach(it => {
        if (it.boardNo == data.boardNo) {
          this.$set(it, 'weight', data.weight)
          this.$set(it, 'length', data.length)
          this.$set(it, 'width', data.width)
          this.$set(it, 'height', data.height)
        }
      })
    },
    generateTag(call) {
      this.$ajax({
        url: "/wms-api/outbound/OutboundBoxRpc/getBoxNo.json",
        method: 'get', loading: true,
        success: (res) => {
          // this.boardNo = res.data
          if (call) call(res.data)
        },
        failure: () => {
        },
        complete: () => {
        }
      })
    },
    scanTrackNumber() {
      this.$refs.formSearch.validate((valid) => {
        if (valid) {
          if (this.searchType == "collect") {
            this.trackList = []
            this.checkCollectRalation(this.searchCode,
              {
                success: (data) => {
                },
              }
            )
            return
          }
          if (this.trackList.some(it => it.trackNumber == this.searchCode)) return this.$message.warning(this.$tt(this.$tt("tip_trackNumber_has_add_finish"), { trackNumber: this.searchCode }))
          if (this.hasCollectTrackList) {
            this.addPackageToCollectRalation(this.searchCode, true)
          } else if (_.isEmpty(this.trackList)) {
            this.addPackageToBoard({
              addCall: (data, searchCode) => {
                this.generateTag((code) => {
                  this.trackList.push(data)
                  this.linkTrackNumber = searchCode
                  this.searchCode = ""
                  this.boardNo = code
                })

              },
              hasPlanCall: (planBoxNo, searchCode) => {
                this.checkCollectRalation(planBoxNo,
                  {
                    success: (data) => {
                      this.addPackageToCollectRalation(searchCode, false)
                    },
                    fail: () => {

                    }
                  }
                )
              }
            })

          } else {
            this.addPackageToBoard({
              addCall: (data, searchCode) => {
                this.trackList.push(data)
                this.linkTrackNumber = searchCode
                this.searchCode = ""
              },
              hasPlanCall: (planBoxNo, searchCode) => {
                return this.$message.error(this.$tt("tip_xxx_face_track_has_collect_relationship", { code: searchCode }))
              }
            })
          }

        } else {
          return false;
        }
      });
    },
    addPackageToBoard({ addCall, hasPlanCall }) {

      this.linkLoading = true
      this.$ajax({
        url: "/wms-api/outbound/OutboundBoxRpc/selectBoxPackage.json",
        method: 'post',
        data: {
          packageNo: this.searchCode
        },
        success: (res) => {
          if (res.data) {
            if (res.data.planBoxNo) {
              if (hasPlanCall) hasPlanCall(res.data.planBoxNo, this.searchCode)
              return
            }
            // if (this.trackList.some(it => it.customerId != res.data.customerId)) {
            //   return this.$message.error(this.$tt("tip_customer_different"))
            // }
            if (this.trackList.some(it => it.supplierId != res.data.supplierId)) {
              return this.$message.error(this.$tt("tip_supplier_different"))
            } else if (this.trackList.some(it => it.bizType != res.data.bizType)) {
              return this.$message.error(this.$tt("tip_toc_tob_no_mix"))
            }

            if (addCall) addCall(res.data, this.searchCode)
          } else {
            this.$message.error(this.$tt('tip_search_no_data'))
          }
        },
        failure: () => {
          // this.linkError = true
        },
        complete: () => {
          this.linkLoading = false
        }
      })
    },
    addPackageToCollectRalation(code, tip, fixItem) {
      if (!code) return
      const track = _.find(this.hasCollectTrackList, it => it.trackNumber == code)
      if (track) {
        if (tip && track.packageFlag != 'Y') {
          this.$message.error(this.$tt("tip_trackNumber_no_check_pack_finish", { trackNumber: track.trackNumber }))
          return
        }
        this.$set(track, 'finish', true)
        if (fixItem) fixItem(track)
        this.trackList.push(track)
        this.linkTrackNumber = track.trackNumber
        this.searchCode = ""
      } else if (tip) {
        this.$message.error(this.$tt("tip_scan_wait_collect_face_track"))
      }
    },
    checkCollectRalation(code, { success, fail }) {
      this.linkLoading = true
      this.hasCollectTrackList = null
      this.$ajax({
        url: "/wms-api/outbound/OutboundBoxRpc/selectBoxPackagesByWbSupplyId.json",
        method: 'post',
        data: {
          supplyId: code
        },
        success: (res) => {
          if (res.data && res.data.packageList && !_.isEmpty(res.data.packageList)) {
            res.data.packageList.forEach(it => {
              it.fileName = res.data.fileName
              it.filePath = res.data.filePath
            })
            this.boardNo = code
            this.hasCollectTrackList = res.data.packageList
            if (success) success(res.data)
          } else {
            this.$message.error(this.$tt('tip_search_no_data'))
          }
        },
        fail: (res) => {
          if (fail) fail(res)
        },
        complete: () => {
          this.linkLoading = false
        }
      })
    },
    summaryMethod({ columns, data }) {
    },
    confirmPackageCheck() {
      if (this.hasCollectTrackList && this.hasCollectTrackList.length != this.trackList.length) {
        // return this.$message.error(this.$tt("tip_scan_wait_collect_face_track"))
        if (this.trackList.length == 0) {
          this.$message.error(this.$tt("tip_scan_wait_collect_face_track"))
          return
        }
        if (this.tableData.some(it => it.boardNo == this.boardNo)) {
          this.$message.error(this.$tt("tip_has_collect_package_code"))
          return
        }
        this.$confirm(this.$tt("tip_confirm_collect_package_when_plan_no_equit_actual",
          { plan: this.hasCollectTrackList.length, actual: this.trackList.length }), this.$tt("label_tip"), {
          type: 'warning'
        }).then(() => {
          this.confirmPackage()
        }).catch(() => {

        });
      } else {
        this.confirmPackage()
      }
    },
    confirmPackage() {
      // if (this.collectionPackType == 'PackMaterial') {
      //   if (_.isEmpty(this.packId)) return this.$message.error(this.$tt('tip_pack_material_type_noEmpty'))
      // } else {
      //   if (_.isEmpty(this.containerId)) return this.$message.error(this.$tt('tip_container_type_no_empty'))
      // }

      const list = []
      this.trackList.forEach((it, i) => {
        let out = {
          rowspan: i == 0 ? this.trackList.length : 0,

          boardNo: this.boardNo,//	string 	集包号
          packageNo: it.trackNumber,//	string 	包裹号
          trackWeight: it.weight,
          trackVolume: it.volume,
          customerId: it.customerId,
          customerCode: it.customerCode,
          customerName: it.customerName,
          packageBoxNos: it.packageBoxNos,
          supplierId: it.supplierId,
          supplierCode: it.supplierCode,
          supplierName: it.supplierName,
          outOrderNo: it.outOrderNo,
          skuCount: it.scansCount,
          weight: null,//	bigdecimal 	包裹重量
          width: null,//	bigdecimal 	长（CM)
          length: null,//	bigdecimal 	宽（CM)
          height: null,//	bigdecimal 	高（CM)

          filePath: it.filePath,
          fileName: it.fileName,

          boxId: this.boxId,
          boxRelationFlag: _.isEmpty(this.hasCollectTrackList) ? 'N' : "Y"
        }
        if (this.collectionPackType == 'PackMaterial') {
          Object.assign(out, {
            packageType: this.packTypeName,
            packageName: this.packName,

            materialStockId: this.packId,
            materialCode: this.packCode,
            materialName: this.packName,
          })
        } else if (this.collectionPackType == 'PackContainer') {
          Object.assign(out, {
            containerType: this.containerType,//	string 	容器类型
            containerName: this.containerCode,//	string 	容器名称
            containerCode: this.containerCode,//	string 	容器名称
          })
        }
        list.push(out)
      })
      this.tableData.push(...list)
      this.boardNo = ""
      this.searchCode = ""
      this.boxId = null
      this.trackList = []
      this.hasCollectTrackList = null

      this.autoPrintAction([_.head(list)])
    },

    autoPrintAction(rows) {
      if (this.autoPrint) {
        this.$refs.print_outbound_pallet.printDefaultOption({ list: rows })
        if (rows.some(it => it.filePath)) {
          this.$refs.print_outbound_pallet.printDefaultOption({ list: rows,  thirdParty: true },)
        }
      }
    },


    changeCollectionPackType(e) {
      this.collectionPackType == e
      if (e == 'PackMaterial') {
        this.containerType = null
        this.containerName = null
        this.containerCode = null

      } else if (e == 'PackContainer') {
        this.packTypeName = null
        this.packName = null
        this.packId = null
        this.packCode = null
        this.packName = null
      }
    },
    pausePackage() {
      this.$confirm(this.$tt('tip_xxx_confirm_action_type', { type: this.$tt('label_pause_package_collection') }), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        const list = this.trackList.map((it, i) => {
          let out = {
            rowspan: i == 0 ? this.trackList.length : 0,
            boardNo: this.boardNo,//	string 	集包号
            packageNo: it.trackNumber,//	string 	包裹号
            trackWeight: it.weight,
            trackVolume: it.volume,

            customerId: it.customerId,
            customerCode: it.customerCode,
            customerName: it.customerName,
            packageBoxNos: it.packageBoxNos,
            supplierId: it.supplierId,
            supplierCode: it.supplierCode,
            supplierName: it.supplierName,
            outOrderNo: it.outOrderNo,
            skuCount: it.scansCount,
            weight: null,//	bigdecimal 	包裹重量
            width: null,//	bigdecimal 	长（CM)
            length: null,//	bigdecimal 	宽（CM)
            height: null,//	bigdecimal 	高（CM)

            boxId: this.boxId,
          }
          return out
        })
        list.forEach(it => {
          it.boxNo = it.boardNo
          it.boxStatus = "PROCESSING"
          it.boxRelationFlag = _.isEmpty(this.hasCollectTrackList) ? 'N' : "Y"
        })
        let data = {
          wmsOutboundBoxSubmitList: list,
        }
        this.$ajax({
          url: "/wms-api/outbound/OutboundBoxRpc/saveWmsOutboundBox.json",
          method: 'post', type: 'json',
          data,
          loading: true,
          success: (res) => {
            this.autoPrintAction([_.head(list)])
            this.$emitPage('outbound>package_collection_record', 'reload')
            this.$message.success(this.$tt('tip_submit_success'))
            this.boxId = null
            this.boardNo = ""
            this.searchCode = ""
            this.trackList = []
            this.hasCollectTrackList = null
          },
          failure: () => {
          },
          complete: () => {
          }
        })
      }).catch(() => {

      });
    },
    reviewConfirm() {
      if (_.isEmpty(this.tableData)) {
        return this.$message.error(this.$tt('tip_please_package_collection_finish'))
      }
      if (this.tableData.some(it => _.isEmpty(it.length) || _.isEmpty(it.width) || _.isEmpty(it.height) || _.isEmpty(it.weight))) {
        return this.$message.error(this.$tt('tip_measure_first'))
      }
      this.$confirm(this.$tt('tip_xxx_confirm_action_type', { type: this.$tt('title_package_collection') }), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        const list = _.cloneDeep(this.tableData)
        list.forEach(it => {
          it.boxNo = it.boardNo
          it.boxStatus = "COMPLETED"
          // if (this.boxId) it.boxId = this.boxId
        })
        let data = {
          wmsOutboundBoxSubmitList: list,
          // boxStatus: "COMPLETED",
        }



        this.$ajax({
          url: "/wms-api/outbound/OutboundBoxRpc/saveWmsOutboundBox.json",
          method: 'post', type: 'json',
          data,
          loading: true,
          success: (res) => {
            this.$emitPage('outbound>package_collection_record', 'reload')
            this.$message.success(this.$tt('tip_submit_success'))
            this.tableData = []
            this.containerType = null
            this.containerId = null
            this.containerCode = null
            this.packId = null
            this.packCode = null
            this.packName = null
            this.packTypeName = null
            this.packTypeId = null
          },
          failure: () => {
          },
          complete: () => {
          }
        })
      }).catch(() => {

      });


    },
  }
};

</script>
